package com.zjp.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

//@RestController
@Controller
public class MyController {
    @RequestMapping({"/index","/"})
    public String toIndex(Model model){
        System.out.println("1.index");
        model.addAttribute("msg", "hello login");

        return "index";
    }
    @RequestMapping("user/update")
    public String update(){
        System.out.println("2.update");
        return "user/update";
    }
    @RequestMapping("user/add")
    public String add(){
        System.out.println("2.add");
        return "user/add";
    }
    @RequestMapping("toLogin")
    public String toLogin(){
        System.out.println("4.toLogin");
        return "login";
    }
    @RequestMapping("unauthorized")
//    @ResponseBody加了这一句就会直接把return里面的字符串返回给前端
    public String unauthorized(){

        return "401";
    }
    @RequestMapping("login")
    public String login(String username, String password, Model model){
        System.out.println("5.login");
        //获取当前用户
        Subject subject = SecurityUtils.getSubject();
        //封装用户的登录数据
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);

        try {
            subject.login(token);//执行登录方法
            return "index";
        }catch (UnknownAccountException e) {//用户名不存在
            model.addAttribute("msg","用户名错误");
            return "login";
        }catch (IncorrectCredentialsException e){
            model.addAttribute("msg", "密码错误");
            return "login";
        }
    }
}
